import { Component } from 'react';
import Taro  from '@tarojs/taro';
import { ScrollView, View, Image, Text } from '@tarojs/components'
import CarInfo from '@/components/CarInfo'
import EmptyView from '@/components/EmptyView'
import { AtButton, AtMessage, AtDivider } from 'taro-ui'
import { connect } from 'react-redux'
import classnames from 'classnames'
import './index.scss'
import { getAnnualCardBalanceList, getRelatedCouponItem } from '@/api/annual'

import dayjs from 'dayjs'
import { cloneDeep } from 'lodash';

type coupon = {
	couponItemId: [number,string]
	mustUse: number
}
type State = {
	scrollTop: number
	btn: any
	selectIndex: number
	availableList: Array<any>
	unavailableList: Array<any>
	typeOptios: any,
	usedCouponItemIds:Array<any>
}
@connect<any>(({  car }) => ({ car }))
export default class AnnualBalanceIndex extends Component<any, State> {
	protected headH: number
	protected bannerImg: string = `${SOURCES_PATH}/img/annual/banner.png`
	protected carLicense: string
	constructor(props) {
		super(props)
		this.state = {
			scrollTop: 0,
			btn: {
				btnText: '去办理', // 去办理, 去使用
				state: 1, // 1, 2
				disabled: false
			},
			selectIndex: 0,
			availableList: [],
			unavailableList: [],
			usedCouponItemIds:[],
			typeOptios: [
				{ type: 1, typeLabel: '可用年卡', lock: false},
				{ type: 2, typeLabel: '不可用年卡', lock: false}
			]
		}
	}
	static options = {
    addGlobalClass: true
  }

	handleChangeNavIndx(index: number) {
		let { selectIndex } = this.state
		this.setState({
			selectIndex: index
		}, () => {
			if (selectIndex !== index) {
				this.getList()
			}
		})
	}
	UNSAFE_componentWillMount() {
		if (this.props.car.carInfo.currentCar) {
			this.carLicense = this.props.car.carInfo.currentCar.carLicense
		}
	}
	componentDidShow() {
		if (this.carLicense) {
			let { typeOptios, selectIndex } = this.state
			typeOptios[0].lock = false
			typeOptios[1].lock = false
			let selectType = typeOptios[selectIndex].type
			this.setState({
				availableList: [],
				unavailableList: [],
				typeOptios,
				usedCouponItemIds:[]
			}, () => {
				this.getList()
			})
		}
	}

	UNSAFE_componentWillReceiveProps(nextProps) {
		if (nextProps.car.carInfo.currentCar && this.carLicense !== nextProps.car.carInfo.currentCar.carLicense) {
			this.carLicense = nextProps.car.carInfo.currentCar.carLicense
			let { typeOptios, selectIndex, availableList, unavailableList  } = this.state
			typeOptios[0].lock = false
			typeOptios[1].lock = false
			let selectType = typeOptios[selectIndex].type
			this.setState({
				availableList: [],
				unavailableList:  [],
				typeOptios
			}, () => {
				this.getList()
			})
		}
	}

	async getList() {
		let { typeOptios, selectIndex, availableList,  unavailableList} = this.state
		let selectType = typeOptios[selectIndex].type
		let lock = typeOptios[selectIndex].lock

		if (lock) return
		Taro.showLoading({
			title: '加载中...',
			mask: true
    })
		let res = await getAnnualCardBalanceList({
			type: selectType,
			carLicense: this.carLicense

		})
		Taro.hideLoading()
		typeOptios[selectIndex].lock = true
		let data = this.forMatData(res.data.data)
		this.setState({
			availableList: selectType === 1 ? data : availableList,
			unavailableList: selectType === 2 ? data : unavailableList,
			typeOptios
		}, () => {
			if (selectType === 1) {
				this.setBtnState()
			}
		})
	}

	forMatData(data: Array<any>) {
		data = data.map(i => {
			return {
				...i,
				coupons: formatCoupons(i.coupons)
			}
		})
		function formatCoupons(coupons: Array<any>) {
			let newCoupons: Array<any> = []
			for(let i in coupons) {
				newCoupons.push({
					...coupons[i],
					date: `${dayjs.unix(coupons[i].startAt).format('YYYY年MM月DD日')}-${dayjs.unix(coupons[i].endAt).format('YYYY年MM月DD日')}`,
					checked: false
				})
			}
			return newCoupons
		}
		return data
	}

	handleCheck(couponIndex: number) {
		let { availableList } = this.state
		let coupons = availableList[0].coupons
		let couponsItem = coupons[couponIndex]
		couponsItem.checked = couponsItem.checked
		this.getRelatedCouponItem(couponsItem)
	}
	async getRelatedCouponItem(couponsItem) {
		let { usedCouponItemIds,availableList } = this.state
		let { carLicense, jekunModelCode } = this.props.car.carInfo.currentCar
		let {	checked, dataMatchRule, timeMark, id, mustRelated, goods, oilProperty } = couponsItem
		let { capacity, goodsId } = goods
		if(checked){ // 取消选中
			let coupons = availableList[0].coupons
			coupons.map(d=>{
				d.checked = false
			})
			this.setState({
				availableList,
			}, () => {
				this.setBtnState()
			})

		}else { // 勾选
			console.log('usedCouponItemIds',usedCouponItemIds)
			let coupons = availableList[0].coupons
			let usedCoupon = []
			for (let i in coupons) {
				if (coupons[i].checked) {
					usedCoupon.push({
						couponItemId: +coupons[i].id,
						mustUse: coupons[i].mustUse,
						minUse: coupons[i].minUse
					})
				}
			}
			const formData = {
				dataMatchRule,
				timeMark,
				itemId: id,
				mustRelated,
				carLicense,
				jekunModelCode,
				selectGoodsId: goodsId,
				capacity,
				oilProperty,
				usedCoupon,
			}
			try {
				Taro.showLoading({
					title: '关联中',
					mask: true
				})
				let res = await getRelatedCouponItem(formData)
				Taro.hideLoading()
				if (!res.data.success) throw new Error('获取失败请稍后重试')
				this.fillFieldAndCheck(checked, res.data.data)
			} catch (error) {
				Taro.showToast({
					title: error.message,
					icon: 'none',
				})
			} finally {
				//Taro.hideLoading()
			}
		}

	}

	fillFieldAndCheck(checkedStatus, data) {
		let { availableList } = this.state
		let coupons = availableList[0].coupons
		console.log('data',data)
		coupons.map(d=>{
			d.checked = false
		})

		// 首先要将usedCouponItemIds 和 已经勾选的作为对比，然后在
		// usedCouponItemIds.push(data)
		coupons.map(item => {
			for(var i=0;i<data.length;i++){
				if(item.id == data[i].couponItemId){
					item.checked = !checkedStatus
					// item.checked = true
					item.mustUse= data[i].mustUse
					item.minUse= data[i].minUse
				}
			}
		})
		availableList[0].coupons = coupons
		this.setState({
			availableList,
		}, () => {
			this.setBtnState()
		})
	}

	setBtnState() {
		let { availableList, btn } = this.state
		if (availableList.length) {
			btn.state = 2
			btn.btnText = '去使用'
			btn.disabled = true
			let coupons = availableList[0].coupons
			for (let i in coupons) {
				if (coupons[i].checked) {
					btn.disabled = false
				}
			}
		} else {
			btn.disabled = false
		}
		this.setState({
			btn
		})
	}

	handleSubmit() {
		// 跳转的时候带一个store：只能在这个门店预约  带一个区域过去，表示，可以选择这个区域下的满足条件的门店，如果什么都没有带过去，就标识用久的逻辑
		const { btn, availableList } = this.state
		// if(){

		// }
		//
		// if(details.isCyCheckCoupon == 1){ // 常悦检测新能源流程
		// 	Taro.navigateTo({ url: '/pages/webview/index/index?path=/check/payment' })
		// 	return
		// }
		if (btn.state === 1) {
			Taro.navigateTo({
				url: '/pages/annual/index/index'
			})
		} else if (btn.state === 2) {
			let coupons = availableList[0].coupons
			let formData:Array<coupon> = []
			for (let i in coupons) {
				if (coupons[i].checked) {
					if(coupons[i].isCyCheckCoupon == 1){ // 常悦检测新能源流程
						let query = {
              storeCode:coupons[i].belongStoreCode,
							couponId:coupons[i].id
          }
						Taro.navigateTo({ url: `/pages/webview/index/index?path=/check/payment&query=${JSON.stringify(query)}` })
						return
					}
					formData.push({
						couponItemId: ''+coupons[i].id,
						mustUse: coupons[i].mustUse
					})
				}
			}
			// 根据区分券的类型，是门店券还是平台券
			Taro.navigateTo({
				url: `/pages/annual/use/index?formData=${JSON.stringify(formData)}`
			})
		}
	}

	render() {
		const scrollStyle = {
			height: '100vh'
		}
		let { scrollTop, btn, typeOptios, selectIndex, availableList, unavailableList} = this.state
		let selectType = typeOptios[selectIndex].type
		let locationInfo = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
		let cityName = locationInfo.name ? locationInfo.name : ''
		let navView = typeOptios.map((item, index) =>
			<View>
					<View key={item.type + index} className={
						classnames('item', {
							'active': item.type === selectType
						})
					} onClick={this.handleChangeNavIndx.bind(this, index)}
					>
						{ item.typeLabel }
					</View>

			</View>
		)
		let availableListView = availableList.map((item, index) =>
			<View key={'item' + index} className='content-item'>
				<View className='cart-title-box'>{cityName}地区门店适用</View>
				<View className='content-item-head'>
					<View className='icon-wrap'>
						<View className='icon'></View>
						<Text className='title'>年卡券</Text>
					</View>
					<Text className='store'>{item.describeText}</Text>
				</View>
				<View className='content-item-body'>
					{ item.coupons.map((coupon, couponIndex) =>
						<View key={'coupon' + couponIndex} className={classnames('content-item-body-item', {
							'checked': coupon.checked
						})} onClick={this.handleCheck.bind(this, couponIndex)}
						>
							<View className='content-item-body-item-left'>
								<Image className='banner-img' mode='aspectFill' lazyLoad={true} src={coupon.goods.thumbnailUrl}></Image>
							</View>
							<View className='content-item-body-item-right'>
								<View className='top'>
									<Text className='title'>{coupon.goods.goodsName}</Text>
									{ coupon.goods.tags && coupon.goods.tags.length > 0 && <View className='specification'>{coupon.goods.tags.join(',')}</View>}
								</View>
								<View>{coupon.canUsedAreaLabel}</View>
								<View className='bottom'>
								<Text className='date'>{coupon.date}</Text>
								</View>
								{ coupon.count > 0 && <Text className='amount'>x{coupon.count}</Text> }
							</View>
						</View>
					)}
				</View>
			</View>
		)

		let unavailableListView = unavailableList.map((item, index) =>
			<View key={'item' + index} className='content-item'>
				<View className='cart-title-box'>其它地区门店适用，请从首页切换城市后使用</View>
				<View className='content-item-head'>
					<View className='icon-wrap'>
						<View className='icon'></View>
						<Text className='title'>年卡券</Text>
					</View>
					<Text className='store'>{item.describeText}</Text>
				</View>
				<View className='content-item-body'>
					{ item.coupons.map((coupon, couponIndex) =>
						<View key={'coupon' + couponIndex} className='content-item-body-item'>
							<View className='content-item-body-item-left'>
								<Image className='banner-img' mode='aspectFill' lazyLoad={true} src={coupon.goods.thumbnailUrl}></Image>
							</View>
							<View className='content-item-body-item-right'>
								<View className='top'>
									<Text className='title'>{coupon.goods.goodsName}</Text>
									{ coupon.goods.tags && coupon.goods.tags.length > 0 && <View className='specification'>{coupon.goods.tags.join(',')}</View>}
								</View>
								<View>{coupon.canUsedAreaLabel}</View>
								<View className='bottom'>
								<Text className='date'>{coupon.date}</Text>
								</View>
								{ coupon.count > 0 && <Text className='amount disabled'>x{coupon.count}</Text> }
							</View>
						</View>
					)}
				</View>
			</View>
		)
		return (
			<View className='annual-balance-wrap'>
				<View className='head-wrap'>
					<View className='car-info'>
						<CarInfo />
					</View>
					<View className='narbar-wrap'>
						{ navView }
					</View>
				</View>
				{ selectType === 1 && process.env.TARO_ENV === 'weapp' &&
					<View className='btn-wrap' >
						<AtButton type='primary' disabled={btn.disabled} onClick={this.handleSubmit.bind(this)}>{btn.btnText}</AtButton>
					</View>
				}
				{ selectType === 2 &&  availableList.length === 0 && unavailableList.length === 0 && process.env.TARO_ENV === 'weapp' &&
					<View className='btn-wrap' >
						<AtButton type='primary' disabled={btn.disabled} onClick={this.handleSubmit.bind(this)}>{btn.btnText}</AtButton>
					</View>
				}
				{/*

				*/}
				<ScrollView className='content-scroll-wrap' enableBackToTop scrollTop={scrollTop} scrollY style={scrollStyle}>
					<View className={classnames('content', {
						'padding': selectType === 1
					})}
					>
						{ selectType === 1 && typeOptios[selectIndex].lock && availableList.length === 0 &&	<EmptyView title='暂无年卡服务' subTitle='办理会员年卡，优惠最高3折，畅享优质服务' /> }
						{ selectType === 2 && typeOptios[selectIndex].lock && unavailableList.length === 0 &&	<EmptyView title='暂无年卡服务' subTitle='办理会员年卡，优惠最高3折，畅享优质服务' /> }
						{ selectType === 1 && availableListView }
						{ selectType === 2 && unavailableListView }
						{ availableList.length > 0 && selectType === 1 && typeOptios[selectIndex].lock && <AtDivider content='我是有底线的~' lineColor='#f5f5f5' fontColor='#ccc' />}
						{ unavailableList.length > 0 && selectType === 2 && typeOptios[selectIndex].lock && <AtDivider content='我是有底线的~' lineColor='#f5f5f5' fontColor='#ccc' />}
					</View>

				</ScrollView>
				<AtMessage />
			</View>
		)
	}
}
